<?php
/**
 * 前端会员基础控制器
 * ============================================================================
 * 网站地址: http://www.pcfcms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小潘 <1131680521@qq.com>
 * Date: 2019-12-21
 */
namespace app\home\controller\user;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
use app\common\controller\Common;

class Base extends Common 
{

    public $usersConfig = [];
    public $users_id = 0;
    public $users = array();

    // 初始化操作
    public function initialize() {
        parent::initialize();
        if(session::get('pcfcms_users_id') > 0 && !empty(session::get('pcfcms_users_id'))){
            $this->users_id = Session::get('pcfcms_users_id');
            $this->users = $this->getUserInfo($this->users_id);
            $this->assign('users_id',$this->users_id); //存储会员ID
            $this->assign('users',$this->users); //存储会员信息
        } else {
            //过滤不需要登陆的行为
            $ctl_act = Request::controller().'/'.Request::action();
            $ctl_all = Request::controller().'/*';
            // 过滤不需要登录的操作
            $filter_login_action = [
                'user.Users/login', // 登录
				'user.Users/reg',   // 注册
                'user.Users/logout', // 退出
                'user.Users/vertify', // 验证码
                'user.Smtpmail/*', // 邮箱发送
                'user.Sms/*', // 短信发送
            ];
            if (!in_array($ctl_act, $filter_login_action) && !in_array($ctl_all, $filter_login_action)) {
                $this->redirect(url('/user/login')->suffix(true)->domain(true)->build());
            }
        }
        // 会员功能是否开启
        $logut_redirect_url = '';
        $this->usersConfig = getUsersConfigData('all');
        if ($this->usersConfig['users_open_reg'] == 0) {
            $logut_redirect_url = '/';
        } else if (session::get('pcfcms_users_id') < 0 && empty($this->users)) { 
            $logut_redirect_url = url('/user/login')->suffix(false)->domain(true)->build();
        }
        if (!empty($logut_redirect_url)) {
            // 清理session并回到首页
            session::set('pcfcms_users_id', null);
            $this->redirect($logut_redirect_url);
        }
    }

    // 获取用户基本信息
    protected function getUserInfo($user_id){
        $data =  Db::name('users')->field('b.*,a.*,a.id as users_id')
                ->alias('a')
                ->join('users_level b', "a.level_id = b.id", 'LEFT')
                ->where('a.id',$user_id)
                ->find();
        empty($data['litpic']) && $data['litpic'] = '/common/images/user.png';
        return $data;
    }
    
}